package alogrithm;

import java.util.HashMap;
import java.util.Map;

/**
 * @author lbw
 * @version 1.0
 * @date 2021/10/5 17:24
 */
public class LRUCacheDemo<K, V> {

    class Node<K, V> {
        K key;
        V value;
        Node<K, V> prev;
        Node<K, V> next;

        public Node() {
            this.prev = this.next = null;
        }

        public Node(K key, V value) {
            this();
            this.key = key;
            this.value = value;
        }
    }


    class DoubleLinkedList<K, V> {
        Node<K, V> head;
        Node<K, V> tail;

        public DoubleLinkedList() {
            head = new Node<>();
            tail = new Node<>();
            head.next = tail;
            tail.prev = head;
        }

        // 添加到头
        public void addHead(Node<K, V> node) {
            node.next = head.next;
            node.prev = head;
            head.next.prev = node;
            head.next = node;
        }

        // 删除结点
        public void removeNode(Node<K, V> node) {
            node.next.prev = node.prev;
            node.prev.next = node.next;
            node.prev = null;
            node.next = null;
        }

        // 获得最后一个节点
        public Node<K, V> getLast() {
            return tail.prev;
        }


    }

    private final int capacitySize;
    private final DoubleLinkedList<K, V> doubleLinkedList;
    private final Map<K, Node<K, V>> map;

    public LRUCacheDemo(int capacitySize) {
        this.capacitySize = capacitySize;
        map = new HashMap<>();
        doubleLinkedList = new DoubleLinkedList<>();
    }

    public int get(int key) {
        if (!map.containsKey(key)) {
            return -1;
        }
        Node<K, V> node = map.get(key);

        doubleLinkedList.removeNode(node);
        doubleLinkedList.addHead(node);

        return (Integer) node.value;
    }

    public void put(K key, V value) {
        if (map.containsKey(key)) {
            final Node<K, V> node = map.get(key);
            node.value = value;
            doubleLinkedList.removeNode(node);
            doubleLinkedList.addHead(node);
        } else {
            if (map.size() >= capacitySize) {
                final Node<K, V> last = doubleLinkedList.getLast();
                map.remove(last.key);
                doubleLinkedList.removeNode(last);
            }
            // 新增一个
            Node<K, V> node = new Node<>(key, value);
            doubleLinkedList.addHead(node);
            map.put(key, node);
        }
    }

    public static void main(String[] args) {
        LRUCacheDemo<Integer, Integer> lruCacheDemo = new LRUCacheDemo<>(3);
        lruCacheDemo.put(1, 1);
        lruCacheDemo.put(2, 2);
        lruCacheDemo.put(3, 3);

        System.out.println(lruCacheDemo.map.keySet());

        lruCacheDemo.put(1, 4);
        System.out.println(lruCacheDemo.map.keySet());
        lruCacheDemo.put(4, 4);
        System.out.println(lruCacheDemo.map.keySet());
    }
}
